package org.chuan.hisports.controller;

import org.chuan.hisports.entity.*;
import org.chuan.hisports.service.*;
import org.chuan.hisports.util.CreatTime;
import org.chuan.hisports.util.ImageUtil;
import org.chuan.hisports.util.JSONResult;
import org.chuan.hisports.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.List;

@Controller("user")
@RequestMapping("user")
public class UserController {

    public String servercode;
    @Autowired
    UserService userService;
    @Autowired
    MemberService memberService;
    @RequestMapping("test")
    @ResponseBody
    public String test(){
        Member member = new Member();
        member.setLasttime("2019-09-09 13:00:00");
        member.setLevel("月费");
        member.setUid("1");

        return "成功";
    }

    /**
     *实现用户注册功能
     * @param phone 手机号
     * @param password 密码
     * @param code 验证码
     * @return 返回json对象
     */
    @RequestMapping("register")
    @ResponseBody
    public JSONResult Register(@RequestParam("phone") String phone,
                               @RequestParam("password") String password,
                               @RequestParam("code") String code) throws Exception {
        System.out.println("防空");
        //验证手机密码是否为空，防止一些bug
        if (phone.equals(null) || password.equals(null)){
            return JSONResult.errorMsg("手机号或密码为空");
        }
        System.out.println("防注册");
        //验证手机号是否被注册
        if (userService.checkPhoneExist(phone)){
            return JSONResult.errorMsg("用户已存在，请登录");
        }
        System.out.println("验证码判定");
        if(!code.equals(servercode)) {
            return JSONResult.errorMsg("验证码错误，请重新输入");
        }
        System.out.println("数据插入");
        //开始插入数据
        User user = new User();
        //获取当前时间
        CreatTime creatTime = new CreatTime();
        LocalDateTime nowtime = creatTime.creatTime();
        String nickname = userService.GenerateUserName(creatTime.userTime(nowtime));
        //设置默认会员名
        user.setNickname(nickname);
        //加密密码
        user.setPassword(MD5Util.encryption(password));
        user.setPhone(phone);
        String uid = userService.register(user);
        System.out.println("注册成功");
        //账户注册成功后，就直接向数据库添加健身房会员信息
        Member member = new Member();
        member.setUid(uid);
        member.setJointime(creatTime.dataTime(nowtime));
        member.setLevel("未付费");
        memberService.insert(member);
        //向真实信息表插入一个带用户id的空数据
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(uid);
        userInfoService.CheckUpOrIn(userInfo);
        return JSONResult.registersuccess("注册成功");

    }

    /**
     * 用户登录，并返回一个用户信息
     * @param phone 手机号
     * @param password 密码
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public JSONResult login(@RequestParam("phone") String phone,
                        @RequestParam("password") String password) throws Exception {
        System.out.println("我开始执行");
        //如果未注册
        if(!userService.checkPhoneExist(phone)){
            return JSONResult.errorMsg("手机号码未注册");
        }
        User user = userService.login(phone,MD5Util.encryption(password));

        if(user == null)
            return JSONResult.errorMsg("手机或密码错误");

        return JSONResult.loginsuccess(user);

    }
    //忘记密码
    @RequestMapping("update/0")
    @ResponseBody
    public JSONResult modifyPassword(
            @RequestParam("phone") String phone,
            @RequestParam("password") String password,
            @RequestParam("code") String code) throws NoSuchAlgorithmException {
        System.out.println("开始执行");
        String mpassword = MD5Util.encryption(password);
        boolean flag = userService.modifyPassword(phone, mpassword);
        if (flag){
            System.out.println("返回");
            return JSONResult.build(200,"密码修改成功",null);
        }

        else{
            return JSONResult.build(502,"新密码不能与原密码相同",null);
        }

    }

    //修改昵称
    @RequestMapping("update/1")
    @ResponseBody
    public JSONResult modifyNickname(@RequestParam("id") String id,
                                 @RequestParam("nickname") String nickname){
        System.out.println("修改用户名开始执行");
        userService.modifyNickname(id, nickname);
        User user = userService.modifyNickname(id, nickname);
        return JSONResult.build(200,"修改成功",user);
    }
    //用户真实信息相关操作
    @Autowired
    UserInfoService userInfoService;
    @RequestMapping("update/2")
    @ResponseBody
    public JSONResult updateUserInfo(UserInfo userInfo){
        userInfoService.CheckUpOrIn(userInfo);
        UserInfo info = userInfoService.select(userInfo.getUid());
        return JSONResult.build(200,"success",info);
    }
    //查询用户真实信息
    @RequestMapping("selectInfo")
    @ResponseBody
    public JSONResult selectInfo(@RequestParam("uid") String uid){
        UserInfo userInfo = userInfoService.select(uid);
        return JSONResult.build(200,"success",userInfo);
    }

    @Autowired
    PhoneCode phoneCode;
    @RequestMapping("getcode")
    @ResponseBody
    public JSONResult getCode(@RequestParam("phone") String phone){
        servercode  = phoneCode.creatCode(phone);
        return JSONResult.build(200,"success",servercode);
    }

    //上传头像,并返回用户信息
    @RequestMapping("upavatar")
    @ResponseBody
    public JSONResult upAvatar(String uid, String pictureFile,
                            HttpServletRequest request) throws IOException {
        ImageUtil imageUtil = new ImageUtil();
        String path = request.getSession().getServletContext().getRealPath("/vacatar");
        System.out.println(uid+" "+pictureFile);
        String datapath = imageUtil.phone(uid,pictureFile,path);
       // String datapath = imageUtil.upload(uid,pictureFile,path);
        //头像路径上传至数据库
        userService.modifyAvatar(uid,"/vacatar/"+datapath);
        //查询当前用户信息
        User user = userService.selectById(uid);
        return JSONResult.build(200,"success",user);
    }

    //查询会员的相关信息
    @RequestMapping("selectmember")
    @ResponseBody()
    public JSONResult selectMember(@RequestParam("uid") String uid){
        Member member = memberService.select(uid);
        return JSONResult.build(200,"success",member);
    }

    //获取会员的健身方案
    @RequestMapping("readSchemeByUid")
    @ResponseBody
    public JSONResult readSchemeByUid(@RequestParam("uid") String uid){
        CoaScheme coaScheme = userService.readSchemeByUid(uid);
        return JSONResult.build(200,"success",coaScheme);
    }
    //获取教练的详细信息
    @Autowired
    CoachService coachService;
    @RequestMapping("readCoachinfo")
    @ResponseBody
    public JSONResult readCoachinfo(@RequestParam("cid") String cid){
        CoachInfo coachInfo = coachService.selectByCid(cid);
        return JSONResult.build(200,"success",coachInfo);
    }

    //获取所有教练
    @RequestMapping("readCoachAll")
    @ResponseBody
    public JSONResult readCoachAll(){
        List<CoachInfo> list = coachService.selectCoachAll();
        return JSONResult.build(200,"success",list);
    }

    //下载文件
    @RequestMapping("downApk")
    public void downApk(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/vacatar")+"/fit.apk";
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
        //设置下载名称
        String filename = "fit.apk";
        //转码，免得中文文件名乱码

        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        //设置缓冲流，免得下载速度过于缓慢
        byte buffer[] = new byte[1024];
        int len = 0;
        while((len = bis.read(buffer)) > 0){
            out.write(buffer,0,len);
            out.flush();
        }
        out.close();
        bis.close();

    }

}
